<template>
  <div>
    <el-card class="search-card">
      <basic-table-form
        ref="formData"
        :colNumOfRow="4"
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      >
      </basic-table-form>
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :showSelectCol="false"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :tableHeight="460"
        :actionColWidth="220"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <el-row slot="content_context" type="flex" justify="start">
          <BtnRender :render="renderBtnsBar" />
        </el-row>
      </basic-table>
    </el-card>
    <!-- 取消计划 -->
    <CancelPlan
      :visible.sync="cancelVisible"
      :planId="planId"
      @getTableData="getTableData"
    />
    <!-- 取回 -->
    <RollBack
      :visible.sync="rollbackVisible"
      :planData="planData"
      @getTableData="getTableData"
    />
  </div>
</template>
<script>
import BasicTableForm from '@/components/supplier/BasicForm';
import BasicTable from '@/components/supplier/BasicTable';
import CancelPlan from './components/CancelPlan';
import RollBack from './components/RollBack';
import { FORM_ITEM_LIST, initTableColumns } from './constants';
import { getBtnsId } from '@/libs/btnsPermission';
import BasicPage from '@/mixins/supplier/basicPage';
import Dict from '@/mixins/supplier/dict';
import {
  queryInspectPlanService,
  exportInspectPlanService,
  deleteInspectPlanService,
} from '@api/supplier/returnVisteManage';
import { createExcelByExport } from '@/utils/bizUtils';
import { getWorkflowJumpUrl } from '@/api/supplier/workflow';
import { getBtnsBar, getTableAction } from '@supplier/utils/btnsUtils';
import BtnRender from '@/components/JSXRender/BtnRender';

export default {
  mixins: [ BasicPage, Dict ], // 分页数据及方法 表单基础方法
  components: {
    BasicTableForm,
    BasicTable,
    CancelPlan,
    RollBack,
    BtnRender
  },
  data () {
    return {
      exportLoading: false,
      dialogVisible: false,
      cancelVisible: false,
      rollbackVisible: false,
      planData: {},
      planId: null,
      fileGroupId: null,
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        columns: initTableColumns(this),
        loading: false
      },
      formData: {
        planName: '', // 计划名称
        planCode: '', // 计划编码
        businessTripPlace: '', // 出差地点
        planTime: '', // 计划时间
        startTime: '', // 计划开始时间
        endTime: '', // 计划结束时间
        businessTripPerson: '', // 出差人员
        vehicle: '', // 交通工具
        status: '', // 计划状态
        createUserId: '', // 创建人
        createTime: '', // 创建时间
        createTimeStart: '', // 创建开始时间
        createTimeEnd: '', // 创建结束时间
      }
    };
  },
  created () {
    this.getTableData();
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnsBar = [
        {
          label: '新增',
          size: 'mini',
          type: 'primary',
          method: this.handleAdd,
          hasAuth: true
        },
      ];
      if (this.supplierExportConfig.returnViste) {
        btnsBar.unshift({
          label: '导出',
          method: this.handleExport,
          loading: this.exportLoading,
          size: 'mini',
          type: 'primary',
          hasAuth: true
        })
      }
      return getBtnsBar(h, btnsBar, this.showBtn);
    },
    /* ‒ 暂存：按钮对应查看、编辑、审批日志；
    ‒ 待审批、按钮对应查看、审批日志；
    ‒ 审批通过：按钮对应查看、录入考察报告、审批日志；
    ‒ 审批驳回：查看、编辑、审批日志。 */
    renderTableBtnAction (h, { row }) {
      // '待提交': 1, '审核中': 10, '审核通过': 20, '审核驳回': 30, '撤回': 40
      const actionBtns = [
        { label: '编辑', method: this.editPlan, hasAuth: true, status: [1, 30, 40] },
        { label: '录入考察报告', method: this.addReport, hasAuth: true, status: [20] },
        {
          label: '审批流',
          method: () => { this.handleViewApprovalFlow(row.requestId) },
          hasAuth: true,
          status: [10, 20, 30]
        },
        { label: '删除', method: this.handleDeletePlan, hasAuth: true, status: [1, 30, 40] },
        { label: '取回', method: this.handleWithdraw, hasAuth: true, status: [10] },
        { label: '取消计划', method: this.handleCancelPlan, hasAuth: true, status: [20] },
      ]
      const actionList = actionBtns.filter(item => item.status.includes(row.status));
      return getTableAction({ h, row, actionList, showBtn: this.showBtn });
    },
    // 初始化查询条件
    initSearchParams () {
      const { planTime = [], createTime = [] } = this.formData;
      const [startTime = '', endTime = ''] = planTime || [];
      const [createTimeStart = '', createTimeEnd = ''] = createTime || [];
      return _.omit({
        ...this.formData,
        startTime,
        endTime,
        createTimeStart,
        createTimeEnd,
      }, 'planTime', 'createTime')
    },
    // 获取表格数据
    async getTableData () {
      let data = {
        ...this.initSearchParams(),
        ...this.pagination
      };
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      const res = await queryInspectPlanService(
        data,
        state => { this.tableInfo.loading = state }
      )
      if (res) {
        const { records, total } = res.result;
        this.tableInfo.list = records;
        this.pagination.total = total;
      }
    },
    // 新增计划
    handleAdd () {
      this.$router.push({ name: 'addPlan' })
    },
    // 导出
    async handleExport () {
      const res = await exportInspectPlanService(
        this.initSearchParams(),
        state => { this.exportLoading = state }
      )
      if (res) {
        createExcelByExport({ excelTitle: '考察计划', res })
      }
    },
    // 编辑计划
    editPlan (row) {
      this.$router.push({ name: 'addPlan', query: { id: row.id } })
    },
    // 查看计划
    viewPlan (row) {
      this.$router.push({ name: 'viewPlan', query: { id: row.id, planState: row.status } })
    },
    // 录入考察报告
    addReport (row) {
      this.$router.push({ name: 'viewPlan', query: { id: row.id, planState: row.status } })
    },
    // 审批日志
    auditLog (row) {
      this.$router.push({ name: 'auditLog', query: { supplierId: row.id, module: 3 } })
    },
    // 查看审批流
    handleViewApprovalFlow (requestId) {
      // 动态获取工作流跳转地址
      getWorkflowJumpUrl({ requestId }).then(({ result }) => {
        window.open(result, '_blank')
      })
    },
    // 取回单据
    handleWithdraw (row) {
      this.rollbackVisible = true;
      this.planData = {
        planCode: row.planCode,
        oaRequestId: row.requestId,
        itemUserId: row.createUserId,
        supplierName: row.supplierName
      }
    },
    // 删除计划
    handleDeletePlan (row) {
      this.$confirm('确定删除此计划吗？', '提示', {
        type: 'warning',
      }).then(() => {
        this.deleteInspectPlanAction(row);
      }).catch(() => {});
    },
    // 删除计划接口调用
    async deleteInspectPlanAction (row) {
      const res = deleteInspectPlanService(
        { planId: row.id },
        state => { this.tableInfo.loading = state }
      )
      if (res) {
        this.$message.success('删除成功')
        this.getTableData()
      }
    },
    // 取消计划
    handleCancelPlan (row) {
      this.planId = row.id;
      this.cancelVisible = true;
    }
  }
};
</script>
